package snail.validators;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import snail.data.UserDAO;
import snail.model.User;

public class registerValidator implements Validator {

    public boolean supports(Class aClass) {
     //   return User.class.equals(aClass);
        return true;
    }

    public void validate(Object obj, Errors errors) {
        User user = (User) obj;

        //fields cannot be empty
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "field.required", "Required field");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "field.required", "Required field");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "field.required", "Required field");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address", "field.required", "Required field");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "postAddress", "field.required", "Required field");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "field.required", "Required field");

        // correct email validation
        if (!errors.hasFieldErrors("email")) {
            if (!user.getEmail().matches("^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Za-z]{2,4}$")) {
                errors.rejectValue("email", "wrong.email", "Email is not valid");
            }
        }

        if (!errors.hasFieldErrors("email")) {
            User u2 = new UserDAO().getByEmail(user.getEmail());
            if (u2 != null) {
                errors.rejectValue("email", "alreadytaken.email", "Email already registered");
            }
            // password length validation
            if (!errors.hasFieldErrors("password")) {
                if (user.getPassword().length() < 6) {
                    errors.rejectValue("password", "short.password", "Password too short");
                }
            }

        }
    }
}
